package com.daisuxia.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.test.SerializeUtil;
import com.daisuxia.back.utils.RequestUtils;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.LianLianConstant;
import com.daisuxia.lianlian.entity.LianlianCardBinSend;
import com.daisuxia.lianlian.entity.LianlianSignGrantRecv;
import com.daisuxia.lianlian.entity.LianlianSignGrantSend;
import com.daisuxia.lianlian.util.LLPayUtil;
import com.daisuxia.lianlian.util.RSAUtil;
import com.daisuxia.risk.service.IOutOrdersService;
import com.daisuxia.web.common.reslult.JsonResult;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.OutOrders;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserCertification;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IInfoIndexService;
import com.daisuxia.web.service.IPushUserService;
import com.daisuxia.web.service.IUserBankService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.test.ThreadPool;
import com.daisuxia.web.util.*;

import redis.clients.jedis.JedisCluster;


/**
 * 用户银行卡信息
 *
 * @name xieyaling
 * @date 20161209
 */
@Controller
public class UserBanKController extends BaseController {
    public final static String SMS_TRADE_FIND_PREFIX = "cardSmsCode_";//Redis找回交易密码key前缀
    public final static int INFECTIVE_SMS_TIME = 300;//短信默认有效时间300秒
    public final static String NEW_BANK_CARD = "LIANLIAN_SIGN_GRANT_USERCARDINFO_";//Redis 旧银行卡KEY前缀
	public final static String SMS_SEND_IN_ONE_MINUTE = "SMS_SEND_IN_ONE_MINUTE_";// Redis某个手机号1分钟内已发送验证码key前缀
	public final static String SMS_SEND_COUNT_MAX = "SMS_SEND_COUNT_MAX";// 发送验证码每天限制条数
	public final static int INFECTIVE_SMS_DAY = 86400;// 短信次数有效期
    Logger logger = Logger.getLogger(UserBanKController.class);
    @Autowired
    private IUserBankService userBankService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IInfoIndexService infoIndexService;
    @Autowired
    private IBorrowOrderService borrowOrderService;
    @Autowired
    private IOutOrdersService outOrdersService;
	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	private IPushUserService pushUserService;
    /**
     * 查询银行列表
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping("credit-card/bank-card-info")
    public void selectBankCardList(HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> json = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "获取失败";
        try {
            List<Map<String, Object>> mapList = userBankService.findAllBankInfo();
            if (mapList != null) {
                List<Map<String, String>> restulList = new ArrayList<Map<String, String>>();
                for (int i = 0; i < mapList.size(); i++) {
                    Map<String, Object> listMap = mapList.get(i);
                    HashMap<String, String> resultMap = new HashMap<String, String>();
                    resultMap.put("bank_id", listMap.get("id") + "");
                    resultMap.put("bank_name", listMap.get("bankName") + "");
                    resultMap.put("url", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/common/web/images/bank/bank_" + listMap.get("bankCode") + ".png");
                    restulList.add(resultMap);
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("item", restulList);
                map.put("tips", "由于邮政储蓄银行不支持还款代扣，建议优先选择其他银行卡。");
                json.put("data", map);
                code = Status.SUCCESS.getName();
                msg = "获取成功";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            json.put("code", code);
            json.put("message", msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
        }
    }

    /**
     * 绑定银行卡
     *
     * @param ll
     */
    @RequestMapping("credit-card/sign-back/{userId}/{orderNo}/{type}")
    public String bindUserBank(Model model, LianlianSignGrantRecv ll, @PathVariable Integer userId, @PathVariable String orderNo,@PathVariable int type) {
        String msg = "绑卡成功";
        logger.error("credit-card/sign-back/" + userId + "/" + orderNo + "/" + type);
        OutOrders outOrders = outOrdersService.findByOrderNo(orderNo);
        if (null != outOrders && OutOrders.STATUS_WAIT.equals(outOrders.getStatus())) {

            OutOrders orders = new OutOrders();
            orders.setOrderNo(orderNo);
            orders.setReturnParams(JSONObject.fromObject(ll).toString());

            if ("0000".equals(ll.getStatus())) {
                User user = userService.searchByUserid(userId);
                if (null != user) {
                    JSONObject obj = JSONObject.fromObject(ll.getResult());
                    // 第一次绑卡 从数据库取
                    if(type == 1){
                        UserCardInfo cardInfo = new UserCardInfo();
                        cardInfo.setUserId(userId);
                        cardInfo.setStatus(UserCardInfo.STATUS_SUCCESS);
                        cardInfo.setAgreeno(obj.getString("agreeno"));
                        userBankService.updateUserBankCard(cardInfo);
                        
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        map.put("userId", userId);
                        this.infoIndexService.authBank(map);//设置状态-第一次绑卡
                       	//地推 绑卡
                    			ThreadPool pool = ThreadPool.getInstance();
                    			pool.execute(new DtThread(UserPushUntil.BANKAPPROVE, userId, null, new Date(), userService,
                    					pushUserService, borrowOrderService,null));
                    }
                    else{
                        // 重新绑卡 从redis取
                        byte[] userCardInfo = jedisCluster.get((NEW_BANK_CARD + userId).getBytes());
                        if (userCardInfo != null) {
                            UserCardInfo zbuserCardInfo = (UserCardInfo) SerializeUtil.unserialize(userCardInfo);
                            if (zbuserCardInfo != null) {
                                zbuserCardInfo.setStatus(UserCardInfo.STATUS_SUCCESS);
                                zbuserCardInfo.setAgreeno(obj.getString("agreeno"));
                                userBankService.updateUserBankCard(zbuserCardInfo);
                                
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("userId", userId);
                                this.infoIndexService.authBankOld(map);//设置状态---重新绑卡
                            }
                        }
                    }
                }
                else{
                    logger.error("credit-card/sign-back/" + userId + "/" + orderNo + "/" + type + " unknow userId");
                }
                orders.setStatus(OutOrders.STATUS_SUC);
            } else {
                if ("1100".equals(ll.getStatus())) {
                    msg = "无效卡号 该商户暂不支持该卡或卡号输入有误,请更换其他银行卡";
                } else {
                    msg = "请使用真实银行卡、身份证信息、手机号信息";
                }
                orders.setStatus(OutOrders.STATUS_OTHER);
            }
            jedisCluster.del((NEW_BANK_CARD + userId).getBytes());
            outOrdersService.updateByOrderNo(orders);
        }
        model.addAttribute("msg", msg);
        return "userinfo/userTemp";
    }

    /**
     * 绑定银行卡
     *
     * @param response
     */
    @RequestMapping("credit-card/sign-to-lianlian")
    public String bindUserToLianLian(HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = this.loginFrontUserByDeiceId(request);
        try {
            model.addAttribute("signpath", jedisCluster.get("LIANLIAN_SIGN_GRANT_PATH_" + user.getId()));
            model.addAttribute("data", jedisCluster.get("LIANLIAN_SIGN_GRANT_PARAM_" + user.getId()));

            logger.info("LIANLIAN_SIGN_GRANT_PATH_" + user.getId() + ":" + jedisCluster.get("LIANLIAN_SIGN_GRANT_PATH_" + user.getId()));
            logger.info("LIANLIAN_SIGN_GRANT_PARAM_" + user.getId() + ":" + jedisCluster.get("LIANLIAN_SIGN_GRANT_PARAM_" + user.getId()));

            jedisCluster.del("LIANLIAN_SIGN_GRANT_PATH_" + user.getId());
            jedisCluster.del("LIANLIAN_SIGN_GRANT_PARAM_" + user.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "userinfo/userTodo";
    }


    /**
     *
     * @return
     */
    private ServiceResult bankCardBin(String userId, String cardNo, String bankId){
        ServiceResult serviceResult = new ServiceResult(ServiceResult.SUCCESS, "校验通过");
        JSONObject resultObject = null;
        try{
            LianlianCardBinSend ll = new LianlianCardBinSend();
            ll.setOid_partner(LianLianConstant.getOidPartner());
            ll.setCard_no(cardNo);
            //加签
            String sginOrigin = LLPayUtil.genSignDataByJavaObject(ll);
            ll.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
            String signParam = JSONUtil.beanToJson(ll);
            logger.info("LIANLIAN_BIN_PARAMS:" + signParam);
            String result = HttpUtil.getInstance().postJson(LianLianConstant.getBankCardBinPath(), signParam);
            logger.info("LIANLIAN_GRANT_RETURN:" + result);
            resultObject = JSONObject.fromObject(result);


            String tablelastName = DateUtil.getDateFormat(new Date(), "yyyyMMdd");
            String orderNo = GenerateNo.nextOrdId();
            OutOrders outOrders = new OutOrders();
            outOrders.setUserId(userId);
            outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
            outOrders.setOrderNo(orderNo);
            outOrders.setAct(OutOrders.ACT_BANK_CARD_BIN);
            outOrders.setReqParams(signParam);
            outOrders.setNotifyParams(sginOrigin);
            outOrders.setReturnParams(result);
            outOrders.setTablelastName(tablelastName);
            if(!resultObject.isEmpty() && !resultObject.isNullObject()){
                if("0000".equals(resultObject.getString("ret_code"))){
                    outOrders.setStatus(OutOrders.STATUS_SUC);
                    if(LianLianConstant.CARD_TYPE_XINYONG.equals(resultObject.getString("card_type"))){
                        serviceResult = new ServiceResult("500", "不支持信用卡绑卡");
                    }
                    else{
                        String bankType = LianLianConstant.bankCodeMap.get(bankId);
                        if(StringUtils.isNotBlank(bankType) && !bankType.equals(resultObject.getString("bank_code"))){
                            serviceResult = new ServiceResult("500", "请确认归属行是否正确");
                        }
                        else if("15".equals(bankId) || (null != bankType && "03050000".equals(bankType))){
                            serviceResult = new ServiceResult("500", "由于民生银行系统维护，暂不支持，请绑定其他卡");
                        }
                    }
                }
                else{
                    outOrders.setStatus(OutOrders.STATUS_OTHER);
                }
            }
            else{
                outOrders.setStatus(OutOrders.STATUS_OTHER);
            }
            outOrdersService.insertByTablelastName(outOrders);
        }
        catch (Exception e){
            logger.error("bankCardBin userId=" + userId + " cardNo=" + cardNo + " resultObject=" + resultObject, e);
            serviceResult = new ServiceResult("500", "变量校验出现异常");
        }
        return serviceResult;
    }

    /**
     * 绑定银行卡
     *
     * @param request
     * @param response
     */
    @RequestMapping("credit-card/add-bank-card")
    public void bindUserBank(HttpServletRequest request, HttpServletResponse response) {
    	String GENERATE_FIND_CODE_CHECK="ADD_BANK-CARD_USER_IDCARD";
        Map<String, Object> json = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "绑定失败";
        try {
            User logUser = this.loginFrontUserByDeiceId(request);
           // logger.info("User : " + logUser.getId());
            if (logUser != null) {
                User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
                if (user.getRealname() != null && !"".equals(user.getRealname()) && "1".equals(user.getRealnameStatus())) {
                    Map<String, String> pams = this.getParameters(request);
                    pams.put("userId", user.getId());
                    pams.put("realName", user.getRealname());
                    String smsCode = request.getParameter("code") == null ? "" : request.getParameter("code");
                    if (smsCode == null || "".equals(smsCode)) {
                        msg = "验证码不能为空";
                        return;
                    }
                    String phone = pams.get("phone") == null ? "" : pams.get("phone");
                    if (phone == null || "".equals(phone)) {
                        msg = "预留手机号码不能为空";
                        return;
                    }
                    String sessionCode = jedisCluster.get(SMS_TRADE_FIND_PREFIX + phone);
                    if (sessionCode == null || "".equals(sessionCode)) {
                        msg = "验证码已失效";
                        return;
                    }
                    else if(!smsCode.equals(sessionCode)){
                        msg = "验证码错误";
                        return;
                    }
                    Long remainTime=checkForFront(GENERATE_FIND_CODE_CHECK, phone);
                	if (remainTime>0) {
                		code=Status.FREQUENT.getName();
                		json.put("time", remainTime);
        				msg = Status.FREQUENT.getValue();
        				return;
        			}
                    JsonResult result = null;
                    ServiceResult serviceResult = bankCardBin(user.getId(), pams.get("card_no"), pams.get("bank_id"));
                    if(!ServiceResult.SUCCESS.equals(serviceResult.getCode())){
                        msg = serviceResult.getMsg();
                        return;
                    }
                    try{
                    	result = userBankService.saveUserBankCard(pams);
                    }catch(Exception e){
                    	logger.error("uk_user_id:"+user.getId());
                    }
                    if(null!=result){
	                    if (result.isSuccessed()) {
	                        code = Status.SUCCESS.getName();
	                        msg = "签约跳转中";
	
	                        String orderNo = GenerateNo.nextOrdId();
	                        //拼接参数
	                        LianlianSignGrantSend li = new LianlianSignGrantSend();
	                        li.setId_no(user.getIdNumber());
	                        li.setCard_no(request.getParameter("card_no"));
	                        li.setUrl_return(RequestUtils.getRequestPath(null) + "/credit-card/sign-back/" + user.getId() + "/" + orderNo + "/1");
	                        li.setUser_id(user.getId());
	                        li.setAcct_name(user.getRealname());
	                        li.setOid_partner(LianLianConstant.getOidPartner());
	                        //加签
	                        String sginOrigin = LLPayUtil.genSignDataByJavaObject(li);
	                        li.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
	
	                        String signParam = JSONUtil.beanToJson(li);
	                        Map<String, String> params = new HashMap<String, String>();
	                        jedisCluster.set("LIANLIAN_SIGN_GRANT_PATH_" + user.getId(), LianLianConstant.getSignGrantPath());
	                        jedisCluster.expire("LIANLIAN_SIGN_GRANT_PATH_" + user.getId(), 300);
	                        jedisCluster.set("LIANLIAN_SIGN_GRANT_PARAM_" + user.getId(), signParam);
	                        jedisCluster.expire("LIANLIAN_SIGN_GRANT_PARAM_" + user.getId(), 300);
	//						params.put("signpath", LianLianConstant.getSignGrantPath());
	                        logger.info("signpath-------->" + RequestUtils.getRequestPath(null) + "/credit-card/sign-to-lianlian");
	                        logger.info("signAndAuthParams-------->" + signParam);
	                        params.put("signpath", RequestUtils.getRequestPath(null) + "/credit-card/sign-to-lianlian");
	                        json.put("data", params);
	
	                        OutOrders outOrders = new OutOrders();
	                        outOrders.setUserId(user.getId());
	                        outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
	                        outOrders.setOrderNo(orderNo);
	                        outOrders.setAct(OutOrders.ACT_SIGN_GRANT);
	                        outOrders.setReqParams(signParam);
	                        outOrdersService.insert(outOrders);
	                    } else {
	                        msg = result.getMsg();
	                    }
                    }
                } else {
                    msg = "请填写个人信息";
                }
            } else {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            json.put("code", code);
            json.put("message", msg);
//            System.out.println(JSONUtil.beanToJson(json));
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
        }
    }

    /**
     * 发送短信验证码
     *
     * @param request
     * @param response
     */
    @RequestMapping("credit-card/get-code")
    public void sendBankCode(HttpServletRequest request, HttpServletResponse response) {
        String GET_CREDIT_CARD = "get_credit_card_";
        String phone = request.getParameter("phone") == null ? "" : request.getParameter("phone");
        Map<String, Object> json = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "获取验证码失败";
        try {
        	User logUser = this.loginFrontUserByDeiceId(request);
        	if(logUser!=null){
                if (phone == null || "".equals(phone)) {
                    msg = "手机号码不能为空";
                    return;
                }
                String deviceId = request.getParameter("deviceId");
                Long remainTime = checkForFront(GET_CREDIT_CARD, deviceId, 60);
                if (remainTime>0) {
                    code=Status.FREQUENT.getName();
                    json.put("time", remainTime);
                    msg = "验证码请求频繁，请稍后重试";
                    return;
                }
                ServiceResult serviceResult = check(request, phone); 
				if (serviceResult.isFail()) {
					code = "-1";
					msg = serviceResult.getMsg();
				}else {
//                System.out.println("isCodeTimePass" + isCodeTimePass);
					String rand = String.valueOf(Math.random()).substring(2).substring(0, 6);// 6位固定长度
					request.getSession().setAttribute("cardSmsCode", rand);
					String smsCountRegister = SMS_SEND_COUNT_MAX + phone;
					Integer smsCount=0;
					if(jedisCluster.get(smsCountRegister)!=null){
						smsCount = Integer.valueOf(jedisCluster.get(smsCountRegister));
					}
					Map<String, String> intervalMap = SysCacheUtils.getConfigMap(BackConfigParams.INTERVAL);
					int SMS_SEND_COUNT_MAX = Integer.valueOf(intervalMap.get("INTERVAL_SMS_COUNT"));
					if(smsCount<=SMS_SEND_COUNT_MAX){
						if (SendSmsUtil.sendSmsCL(phone, rand)) {
							if(smsCount==0){
								jedisCluster.setex(smsCountRegister,INFECTIVE_SMS_DAY, String.valueOf(smsCount+1));
							}
							//存入redis
							jedisCluster.set(SMS_TRADE_FIND_PREFIX + phone, rand);
							jedisCluster.expire(SMS_TRADE_FIND_PREFIX + phone, INFECTIVE_SMS_TIME);
							code = "0";
							msg = "成功获取验证码";      //cardSmsCode_18516777211_      cardSmsCode_18519777211_
						}
					}else{
						msg = "24小时内您的验证码发送次数已经超过上线";
					}
				}
        	}else{
        		msg = "登录已失效，请重新登录。";
        	}
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            json.put("code", code);
            json.put("message", msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
        }
    }

    /**
     * 获取认证列表
     *
     * @param request
     * @param response
     */
    @RequestMapping("credit-card/get-verification-info")
    public void getVerificationInfo(HttpServletRequest request, HttpServletResponse response) {
        String telephone = request.getParameter("mobilePhone");
        Map<String, Object> json = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "获取失败";
        try {
            User logUser = this.loginFrontUserByDeiceId(request);
            if (logUser != null) {
                User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
                List<UserCertification> mapList = userService.findCerticationList();
                if (mapList != null) {
                	int mustBeCount = 0;
                    Map<String, Object> cret = userService.checkUserCalendar(Integer.parseInt(logUser.getId()));
                    List<Map<String, Object>> restulList = new ArrayList<Map<String, Object>>();
                    List<Map<String, Object>> isMustBeList = new ArrayList<Map<String, Object>>();
                    List<Map<String, Object>> noMustBeList = new ArrayList<Map<String, Object>>();
                    for (UserCertification certi : mapList) {
                    	if (certi.getTitle().contains("支付宝认证")) {
							continue;
						}
                        HashMap<String, Object> resultMap = new HashMap<String, Object>();
                        resultMap.put("title", certi.getTitle());
                        resultMap.put("subtitle", certi.getDescribe());
                        resultMap.put("tag", certi.getTag());
                        if (certi.getUrl() != null && !"".equals(certi.getUrl())) {
                            resultMap.put("url", certi.getUrl());
                        }
                        if(null != telephone && "cardInfo".equals(certi.getCode())){
                            resultMap.put("url", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/lianlianBindCard/credit-card/firstUserBank");
                        }
                        String operator = checkCertiPams(cret, certi.getCode());
                        String[] logoImg = certi.getLogoImg().split(";;");
                        String logoImgStr = "";
                        if ("未完善".equals(operator)) {
                            resultMap.put("status", 0);
                            resultMap.put("operator", operator);
                            if (logoImg.length >= 2) {
                            	logoImgStr = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" + logoImg[1];
							}else{
								logoImgStr = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" + logoImg[0];
							}
                        } else {
                            if ("cardInfo".equals(certi.getCode())) {
                                UserCardInfo info = userService.findUserBankCard(Integer.parseInt(logUser.getId()));
                                if (info != null) {
                                    String idCard = info.getCard_no();
                                    if (idCard.length() > 4) {
                                        idCard = info.getBankName() + "(" + idCard.substring(idCard.length() - 4, idCard.length()) + ")";
                                    } else {
                                        idCard = info.getBankName() + "(" + idCard + ")";
                                    }
                                    resultMap.put("operator", "<font color=\"#ff5145\" size=\"3\">" + idCard + "</font>");
                                }
                            } else {
                                resultMap.put("operator", "<font color=\"#ff5145\" size=\"3\">已填写</font>");
                            }
                            if (certi.getMustBe() == 1) {  //为必填已填写统计填写认证数量
                            	if (!certi.getTitle().equals("收款银行卡")) {
                            		mustBeCount++;
                            	}
                            }
                            logoImgStr = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" + logoImg[0];
                            resultMap.put("status", 1);
                        }
                        resultMap.put("logo", logoImgStr);
                        if (certi.getMustBe() == 1) {
                            resultMap.put("title_mark", "<font color=\"#ff8003\" size=\"3\">(必填)</font>");
                            if (!certi.getTitle().equals("收款银行卡")) {  //2.2.0版本认证中心不需要收款银行卡
                            	isMustBeList.add(resultMap);
							}
                        } else {
                            resultMap.put("title_mark", "<font color=\"#999999\" size=\"3\">(选填)</font>");
                            noMustBeList.add(resultMap);
                        }
                        restulList.add(resultMap);
                    }
                    Map<String, Object> map = new HashMap<String, Object>();
                    Map<String, Object> listMap = new HashMap<String, Object>();
                    listMap.put("list", restulList);
                    listMap.put("isMustBeList", isMustBeList);
                    listMap.put("noMustBeList", noMustBeList);
                    if (mustBeCount == 1) {
                    	mustBeCount = 25;
					}else if (mustBeCount == 2) {
                    	mustBeCount = 50;
					}else if (mustBeCount == 3) {
                    	mustBeCount = 75;
					}else if (mustBeCount >= 4) {
                    	mustBeCount = 100;
					}
                    listMap.put("mustBeCount", mustBeCount);
                    if ("1".equals(user.getRealnameStatus())) {
                        listMap.put("real_verify_status", "1");
                    } else {
                        listMap.put("real_verify_status", "0");
                    }
                    if ("1".equals(cret.get("emergencyInfo") == null ? "" : cret.get("emergencyInfo").toString())) {
                        listMap.put("contacts_status", "1");
                    } else {
                        listMap.put("contacts_status", "0");
                    }
                    map.put("item", listMap);
                    json.put("data", map);
                    code = Status.SUCCESS.getName();
                    ;
                    msg = "success";
                }
            } else {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            json.put("code", code);
            json.put("message", msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
        }
    }

    public String checkCertiPams(Map<String, Object> certiMap, String key) {
        String operator = "未完善";
        if (certiMap != null) {
            int switchKey = certiMap.get(key) == null || "".equals(certiMap.get(key).toString()) ? 0 : Integer.parseInt(certiMap.get(key).toString());
            switch (switchKey) {
                case 1:
                    operator = "已填写";
                    break;
                default:
                    break;
            }
        }
        return operator;
    }

    /**
     * 去向已绑定银行卡页面
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping("credit-card/card-list")
    public String toUerbankCard(HttpServletRequest request, HttpServletResponse response, Model model) {
        User logUser = this.loginFrontUserByDeiceId(request);
        if (logUser != null) {
            UserCardInfo info = userService.findUserBankCard(Integer.parseInt(logUser.getId()));
            model.addAttribute("bankName", info.getBankName());
            model.addAttribute("deviceId", request.getParameter("deviceId"));
            model.addAttribute("mobilePhone", request.getParameter("mobilePhone"));
            String idCard = info.getCard_no();
            if (idCard != null && idCard.length() > 5) {
                idCard = idCard.substring(0, 4) + "****" + idCard.substring(idCard.length() - 4, idCard.length());
            }
            model.addAttribute("bankCard", idCard);
            String bankPhone = info.getPhone();
            if (idCard != null && idCard.length() > 5) {
                bankPhone = bankPhone.substring(0, 3) + "****" + bankPhone.substring(bankPhone.length() - 4, bankPhone.length());
            }
            model.addAttribute("bankPhone", bankPhone);
        } else {
            model.addAttribute("msg", "登录已失效,请重新登录");
        }
        return "userinfo/userBank";
    }

    /**
     * 重新绑定银行卡页面
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("credit-card/againUserBank")
    public String againUserBank(HttpServletRequest request, HttpServletResponse response, Model model) {
        User logUser = this.loginFrontUserByDeiceId(request);
        List<Map<String, Object>> mapList = userBankService.findAllBankInfo();
        model.addAttribute("bankList", mapList);
        if (logUser != null) {
        	UserCardInfo info = userService.findUserBankCard(Integer.parseInt(logUser.getId()));
            model.addAttribute("deviceId", request.getParameter("deviceId"));
            model.addAttribute("mobilePhone", request.getParameter("mobilePhone"));
            User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
            model.addAttribute("realName", user.getRealname());
            model.addAttribute("cardId",info.getId());
        } else {
            model.addAttribute("msg", "登录已失效,请重新登录");
        }
        return "userinfo/againUserBank";
    }

    /**
     * 重新绑定银行卡
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping("credit-card/updateBankCard")
    public void updateBankCard(HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> json = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "绑定失败";
        try {
            User logUser = this.loginFrontUserByDeiceId(request);
            if (logUser != null) {
                Integer checkResult = borrowOrderService.checkBorrow(Integer.parseInt(logUser.getId()));
                if (1 == checkResult) {
                    msg = "您有借款申请正在审核或未还款完成，暂不能修改银行卡。";
                    return;
                }
                User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
                if (user.getRealname() != null && !"".equals(user.getRealname()) && "1".equals(user.getRealnameStatus())) {
                    Map<String, String> pams = this.getParameters(request);
                    pams.put("userId", user.getId());
                    pams.put("realName", user.getRealname());
                    String smsCode = request.getParameter("code") == null ? "" : request.getParameter("code");
                    if (smsCode == null || "".equals(smsCode)) {
                        msg = "验证码不能为空";
                        return;
                    }
                    String phone = pams.get("phone") == null ? "" : pams.get("phone");
                    if (phone == null || "".equals(phone)) {
                        msg = "预留手机号码不能为空";
                        return;
                    }
                    String sessionCode = jedisCluster.get(SMS_TRADE_FIND_PREFIX + phone);
                    if (sessionCode == null || "".equals(sessionCode) || !smsCode.equals(sessionCode)) {
                        msg = "验证码已失效";
                        return;
                    }
                    ServiceResult serviceResult = bankCardBin(user.getId(), pams.get("card_no"), pams.get("bank_id"));
                    if(!ServiceResult.SUCCESS.equals(serviceResult.getCode())){
                        msg = serviceResult.getMsg();
                        return;
                    }
                    JsonResult result = userBankService.updateUpserBankCard(pams);
                    if (result.isSuccessed()) {
                        code = Status.SUCCESS.getName();
                        msg = "绑定成功";
                        UserCardInfo cardInfo = (UserCardInfo) result.getData();
                        if (cardInfo != null) {
                            byte[] usrSerialize = SerializeUtil.serialize(cardInfo);
                            jedisCluster.set((NEW_BANK_CARD + user.getId()).getBytes(), usrSerialize);
                            jedisCluster.expire((NEW_BANK_CARD + user.getId()).getBytes(), FRONT_USER_EXIST_TIME);
                        }
                        String orderNo = GenerateNo.nextOrdId();
                        //拼接参数
                        LianlianSignGrantSend li = new LianlianSignGrantSend();
                        li.setId_no(user.getIdNumber());
                        li.setCard_no(pams.get("card_no"));
                        li.setUrl_return(RequestUtils.getRequestPath(null) + "/credit-card/sign-back/" + user.getId() + "/" + orderNo + "/2");
                        li.setUser_id(user.getId());
                        li.setAcct_name(user.getRealname());
                        li.setOid_partner(LianLianConstant.getOidPartner());
                        //加签
                        String sginOrigin = LLPayUtil.genSignDataByJavaObject(li);
                        li.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
                        String signParam = JSONUtil.beanToJson(li);
//                        System.out.println("signAndAuthParams:" + li);
                        logger.info("SIGN_GRANT_"  + orderNo + signParam);
                        jedisCluster.set("LIANLIAN_SIGN_GRANT_PATH_" + user.getId(), LianLianConstant.getSignGrantPath());
                        jedisCluster.expire("LIANLIAN_SIGN_GRANT_PATH_" + user.getId(), 300);
                        jedisCluster.set("LIANLIAN_SIGN_GRANT_PARAM_" + user.getId(), signParam);
                        jedisCluster.expire("LIANLIAN_SIGN_GRANT_PARAM_" + user.getId(), 300);

                        OutOrders outOrders = new OutOrders();
                        outOrders.setUserId(user.getId());
                        outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
                        outOrders.setOrderNo(orderNo);
                        outOrders.setAct(OutOrders.ACT_SIGN_GRANT);
                        outOrders.setReqParams(signParam);
                        outOrdersService.insert(outOrders);
                    } else {
                        msg = result.getMsg();
                    }
                } else {
                    msg = "请填写个人信息";
                }
            } else {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            json.put("code", code);
            json.put("message", msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
        }
    }

    /**
     * 更多信息页面
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("credit-web/more")
    public String more(HttpServletRequest request, HttpServletResponse response, Model model) {
        User logUser = this.loginFrontUserByDeiceId(request);
        if (logUser != null) {
            model.addAttribute("deviceId", request.getParameter("deviceId"));
            model.addAttribute("mobilePhone", request.getParameter("mobilePhone"));
            User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
            model.addAttribute("qq", user.getQq());
            model.addAttribute("tobaoaccount", user.getTaobaoAccount());
            model.addAttribute("tobaoaccount", user.getTaobaoAccount());
            model.addAttribute("email", user.getEmail());
            model.addAttribute("wechatAccount", user.getWechatAccount());
        } else {
            model.addAttribute("msg", "登录已失效,请重新登录");
        }
        return "userinfo/userMore";
    }

    /**
     * 保存用户更多信息
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping("credit-card/saveMore")
    public void saveMore(HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> json = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "保存失败";
        try {
            Map<String, String> params = this.getParameters(request);
            User logUser = this.loginFrontUserByDeiceId(request);
            if (logUser != null) {
                User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
                user.setQq(params.get("qq"));
                user.setWechatAccount(params.get("wechatAccount"));
                user.setTaobaoAccount(params.get("tobaoaccount"));
                user.setEmail(params.get("email"));
                userService.updateByPrimaryKeyUser(user);
                code = "0";
                msg = "信息保存成功";
                String telephone = request.getParameter("mobilePhone");
                if(StringUtils.isNotBlank(telephone)){
                    json.put("isNew", "true");
                }
            } else {
                code = "-2";
                msg = "登录已失效.请重新登录";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            json.put("code", code);
            json.put("message", msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
        }
    }

    /**
     * 提额列表，目前写死的，前端只是展示
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping("credit-card/get-card-info")
    public void selectCardInfo(HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> json = new HashMap<String, Object>();

        String code = Status.FAILD.getName();
        String msg = "获取失败";
        String resultJson = "";
        try {
            User logUser = this.loginFrontUserByDeiceId(request);
            if (logUser != null) {

                resultJson = "{\"code\":0,\"message\":\"success\",\"data\":{\"item\":{\"my_amount\":" + logUser.getAmountMax() + ",\"amount_list\":[{\"amount\":2000,\"lock\":1},{\"amount\":3000,\"lock\":1},{\"amount\":4000,\"lock\":1},{\"amount\":5000,\"lock\":1}],\"url\":\"http://www.hao123.com/?amount=\"}}}";

            } else {
                resultJson = "{\"code\":0,\"message\":\"success\",\"data\":{\"item\":{\"my_amount\":1000,\"amount_list\":[{\"amount\":2000,\"lock\":1},{\"amount\":3000,\"lock\":1},{\"amount\":4000,\"lock\":1},{\"amount\":5000,\"lock\":1}],\"url\":\"http://www.hao123.com/?amount=\"}}}";

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//			json.put("code",code);
//			json.put("message",msg);
            JSONUtil.toObjectJson(response, resultJson);
//			JSONUtil.toObjectJson(response, JSONUtil.beanToJson(json));
        }
    }
}
